import { fileURLToPath, URL } from "node:url";

import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import legacy from "@vitejs/plugin-legacy";

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // console.log(command);
  // console.log(mode);
  let config = {};
  if (mode == "serve") {
    config = {
      //dev 独有的配置
    };
  } else {
    config = {
      //build独有配置
    };
  }
  //根据当前工作目录中的mode 加载.env文件
  //第二个参数是一个绝对路径
  //设置第三个参数为''来加载所有的环境变量，而不管是否由`VITE_`前缀
  const env = loadEnv(mode, process.cwd());
  // console.log(env);
  return {
    ...config,
    //插件注入
    plugins: [
      vue(),
      vueJsx(),
      legacy({
        targets: ["defaults", "not IE 11"],
      }),
    ],
    //路径别名
    resolve: {
      alias: {
        "@styles": "/src/assets/styles",
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    //css模块内容支持小驼峰引入
    css: {
      modules: {
        localsConvention: "camelCase",
      },
    },
    //跨域配置
    server: {
      open: false,
      host: "127.0.0.1",
      port: 3456,
      proxy: {
        "^/api/": {
          target: env.VITE_BASE_URL,
          changeOrigin: true /* 允许跨域标识 */,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
    build: {
      target: "es2015",
    },
  };
});
